package com.thghh.jreble;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Map;

import com.zeroturnaround.licensing.UserLicense;

/**
 * com.thghh.jreble.UserLicenseHandler
 * 
 * @author pengzhikang
 * @date 2018年4月18日下午7:53:46
 * @since 1.0
 */
public class UserLicenseHandler {

    private File jrebelFile;

    public UserLicenseHandler(File jrebleFile) {
        this.jrebelFile = jrebleFile;
    }

    public File generateNewJrebleLicense() throws ClassNotFoundException, IOException {
        UserLicense userLicense = UserLicense.loadInstance(jrebelFile);
        // 
        Map<String, Object> dataMap = getMap(userLicense);
        byte[] licenseBuf = serializableMap(dataMap);
        userLicense.setLicense(licenseBuf);
        // 
        File newLic = new File("F://jrebel-crack.lic");
        ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(newLic)));
        oos.writeObject(userLicense);
        oos.flush();
        close(oos);
        return newLic;
    }

    private Map<String, Object> getMap(UserLicense userLicense) {
        Map<String, Object> dataMap = null;
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new ByteArrayInputStream(userLicense.getLicense()));
            Object obj = ois.readObject();
            dataMap = (Map<String, Object>) obj;
            // 设置启动时的打印注释
            dataMap.put("Comment", "*** Use for study only! ***");
            // 设置为商业full版本
            dataMap.put("commercial", "true");
            dataMap.put("Type", "perpetual");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(ois);
        }
        return dataMap;
    }

    public byte[] serializableMap(Map<String, Object> dataMap) {
        byte[] licenseBuf = null;
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        try {
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(dataMap);
            oos.flush();
            bos.flush();
            licenseBuf = bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(bos, oos);
        }

        return licenseBuf;
    }

    public void close(Closeable... closeables) {
        for (Closeable closeable : closeables) {
            if (closeable != null) {
                try {
                    closeable.close();
                } catch (IOException e) {
                }
            }
        }
    }
}
